const Answer = require('../models/answers');

class AnswerCtl{
    //答案查询
    async find(ctx){
        //limit 第几个开始  skip跳过多少个取多少个  Math.max选最大的一项 RegExp正则匹配
        const { per_page = 10 } = ctx.query;
        const page = Math.max(ctx.query.page * 1,1)-1;
        const perPage = Math.max(per_page * 1,1);
        const q = new RegExp(ctx.query.q) 
        ctx.body = await Answer.find({content: q,questionId: ctx.params.questionId}).limit(perPage).skip(page * perPage);
    }
    //查询某个答案可存在
    async checkAnswercExist(ctx, next){
        console.log(ctx.state.user)
        const answers = await Answer.findById(ctx.params.id).select('+answerer');
        ctx.state.answer = answers;
        if(!answers){ ctx.throw(404,'答案不存在')}
        //只有在删改查答案的时候才检查此逻辑，赞和踩答案的时候不检查
        if(ctx.params.questionId && answer.questionId !== ctx.params.questionId){
            ctx.throw(404,'该问题下没有此答案')
        }
        await next();
    }
     //判断该话题是否是该用户的中间件
     async checkAnswerer(ctx, next){
        const { answer } = ctx.state;
        console.log(answer)
        console.log(ctx.state.user)
        if(answer.answerer.toString() !== ctx.state.user._id){ ctx.throw('403','没有权限')}
        await next();
    }
    //查询某个答案
    async findById(ctx){
        const { fields = '' } = ctx.query;
        const seletFields = fields.split(';').filter(f => f).map(f => '+' + f).join("");
        const answers = await Answer.findById(ctx.params.id).select(seletFields).populate('answerer topics');
        ctx.body = answers;
    }
    //创建答案
    async create(ctx){
        ctx.verifyParams({
            content: { type: 'string', required: true }
        })
        const answers = await new Answer({...ctx.request.body, answerer: ctx.state.user._id, questionId: ctx.params.questionId}).save();
        ctx.body = answers;
    }
    //修改答案
    async update(ctx){
        console.log(ctx.state.user)
        ctx.verifyParams({
            content: { type: 'string', required: true }
        })
        await ctx.state.answer.update(ctx.request.body);
        //这个topic是更新前的信息 要跟新后的信息需要自己去撸 这里不重要
        ctx.body = ctx.state.answer;
    }
    //删除某个答案
    async delete(ctx){
        await Answer.findByIdAndRemove(ctx.params.id ); 
        ctx.status = 204;
    }
}

module.exports=new AnswerCtl();